package com.szml.task;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.szml.constants.BasicProductStatusConstants;
import com.szml.constants.StockConstans;
import com.szml.entity.OperationRecord;
import com.szml.entity.ProductBasic;
import com.szml.entity.ProductDetails;
import com.szml.mapper.ProductBasicMapper;
import com.szml.mapper.ProductDetailsMapper;
import com.szml.mapper.UserMapper;
import com.szml.service.OperationRecordService;
import com.szml.service.ProductBasicService;
import com.szml.service.ProductDetailsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 定时任务类，完成类似定时上下线功能
 * **/
@Slf4j
@Component
public class ScheduledTasks {
    //装配ProductBasicService方便我们对商品基本信息操作
    @Autowired
    private ProductBasicService productBasicService;
    @Autowired
    private ProductBasicMapper productBasicMapper;
    @Autowired
    private OperationRecordService operationRecordService;

    @Autowired
    private ProductDetailsService productDetailsService;
    @Autowired
    private ProductDetailsMapper productDetailsMapper;
    @Autowired
    private UserMapper userMapper;
    // 定时任务，每分钟执行一次
    @Scheduled(fixedRate = 60000)
    public void updateProductStatus()
    {
        // 获取当前时间
        LocalDateTime now = LocalDateTime.now();

        // 查询所有即将上线的商品
        List<ProductBasic> productsToBeOnline = productBasicService.findProductsToBeOnline(now);

        log.info("需要上线的数组{}",productsToBeOnline);
        //保存该商品的id

        Long[] ids=extractProductIds(productsToBeOnline);
        Long[]  onuserid=extractUserIds(productsToBeOnline);
        for (ProductBasic product : productsToBeOnline) {
            product.setProductOnlineState(BasicProductStatusConstants.ONLINE_OK); // 设置商品状态为上线
            productBasicService.updateById(product); // 更新商品状态
        }
        if (ids.length!=0)
        {
            //不为空，在对操作记录表进行新增
            log.info("需要上线的产品id{}",ids);
            log.info("需要上线的用户id{}",onuserid);
            addoptionrecord(ids,onuserid,BasicProductStatusConstants.ONLINE,"定时操作");
        }
        // 查询所有即将下线的商品
        List<ProductBasic> productsToBeOffline = productBasicService.findProductsToBeOffline(now);
        //查询基本信息
        Long[] idsoff=extractProductIds(productsToBeOffline);
        Long[] offuserid=extractUserIds(productsToBeOffline);
        for (ProductBasic product : productsToBeOffline) {
            product.setProductOnlineState(BasicProductStatusConstants.ONLINE_NO); // 设置商品状态为下线
            productBasicService.updateById(product); // 更新商品状态
        }
        if (idsoff.length!=0)
        {
            //不为空，在对操作记录表进行新增
            addoptionrecord(idsoff,offuserid,BasicProductStatusConstants.UNONLINE,"定时操作");
        }
    }
    /**
     * 新增操作记录表的操作
     * **/
    private void addoptionrecord(Long[] ids,Long[] userid,String whichStatus,String remark) {
        //当前索引
        int i=0;
        //对操作记录表进行新增
        List<OperationRecord> records = new ArrayList<>();
        for (Long productId : ids) {
            OperationRecord record = new OperationRecord();
            record.setProductId(productId);
            record.setStatus(whichStatus); // 设置状态值
            record.setOperateTime(LocalDateTime.now()); // 设置操作时间
            //record.setOperator(BaseContext.getLoginVO().getName()); // 设置操作人
            String name=userMapper.selectById(userid[i]).getName();
            log.info("name{}",name);
            record.setOperator(name);
            record.setRemark(remark); // 设置备注
            records.add(record);
            i++;//索引加一
        }
        operationRecordService.batchInsert(records);
    }

    /**
     * 将基本信息对象的id转储为一个ids
     * **/
    private  Long[] extractProductIds(List<ProductBasic> productBasics) {
        // 创建一个新的Long[]数组来存储productIds
        Long[] ids = new Long[productBasics.size()];

        // 遍历List中的每个ProductBasic对象
        for (int i = 0; i < productBasics.size(); i++) {
            // 获取当前ProductBasic对象的productId
            ids[i] = productBasics.get(i).getProductId();
        }

        // 返回包含所有productId的Long[]数组
        return ids;
    }
    /**
     * 查询并返回基本信息表数组的userid数组
     * **/
    private  Long[] extractUserIds(List<ProductBasic> productBasics) {
        // 创建一个新的Long[]数组来存储productIds
        Long[] ids = new Long[productBasics.size()];

        // 遍历List中的每个ProductBasic对象
        for (int i = 0; i < productBasics.size(); i++) {
            // 获取当前ProductBasic对象的productId
            ids[i] = productBasics.get(i).getUserId();
        }

        // 返回包含所有productId的Long[]数组
        return ids;
    }


    /**
     *
     * 库存管理，主要实现库存为0
     *的时候主动下线商品
     * **/

    @Scheduled(fixedRate = 6000)
    private void stockmanagement()
    {
        //查出当前的库存小于等于0的商品详细信息列表
        //构造查询条件,查询出所有库存小于等于0的商品详细信息
        QueryWrapper<ProductDetails> queryWrapper=new QueryWrapper<>();
        queryWrapper.le("remaining_stock", StockConstans.STOCK_IS_NULL);
        // 执行查询，获取所有关联的detail_id
        List<ProductDetails> productsWithPendingStatus = productDetailsMapper.selectList(queryWrapper);
        // 执行查询，获取所有即将上线的商品的detail_id
        List<Long> detailIds = productsWithPendingStatus.stream()
                .map(ProductDetails::getPDetailId)
                .collect(Collectors.toList());
        log.info("库存小于等于0的所有商品详细id{}",detailIds);
        if (!detailIds.isEmpty())
        {
            //创建一个Basicproduct查询条件

            QueryWrapper<ProductBasic> queryWrapperBasic=new QueryWrapper<>();
            queryWrapperBasic.in("product_details_id",detailIds);
            queryWrapperBasic.eq("product_online_state",BasicProductStatusConstants.ONLINE_OK);
            //将所有关联的商品基本信息对象存储在list里面
            List<ProductBasic> productBasicList=productBasicMapper.selectList(queryWrapperBasic);
            if (!productBasicList.isEmpty())
            {
                for (ProductBasic product : productBasicList) {
                    product.setProductOnlineState(BasicProductStatusConstants.ONLINE_NO); // 设置商品状态为下线
                    productBasicService.updateById(product); // 更新商品状态
                }

                //查询基本信息
                Long[] idsoff=extractProductIds(productBasicList);
                Long[] offuserid=extractUserIds(productBasicList);
                //不为空，在对操作记录表进行新增
                addoptionrecord(idsoff,offuserid,BasicProductStatusConstants.UNONLINE,StockConstans.STOCK_IS_ZERO);
            }

        }

    }
}
